import { Component, Vue } from 'vue-property-decorator'
import styles from './layout.less'

import { State, Action, Mutation } from 'vuex-class'
import { RootState } from '@/store'
import { LoginState } from '@/store/modules/login'
import { ElForm } from 'element-ui/types/form'

const checkName = (rule: any, value: any, callback: any) => {
  const reg = /([0-9]$)|(([a-zA-Z+\\.?\\·?a-zA-Z+]{1,20}$)|([\u4e00-\u9fa5+\\·?\u4e00-\u9fa5+]{1,20}$))/ // 仅支持中英文与阿拉伯数字 支持“·”分割 最大长度不超过20位
  if (!reg.test(value)) {
    return callback(new Error('请输入正确的姓名'))
  }
  callback()
}

const loginRule = {
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    {
      pattern: /^1[0-9]{10}$/,
      message: '手机号格式不正确',
      trigger: 'blur',
    },
  ],
  licenseNumber: [
    { required: true, message: '请输入身份证号码', trigger: 'blur' },
    {
      pattern: /^(([0-9]{14})|([0-9]{17}))([0-9]|X|x)$/,
      message: '身份证格式不正确',
      trigger: 'blur',
    },
  ],
  username: [
    { required: true, message: '请输入申请人姓名', trigger: 'blur' },
    {
      min: 1,
      max: 20,
      message: '长度在 1 到 20 个字符',
      trigger: 'blur',
    },
    { validator: checkName, trigger: 'blur' },
  ],
  mobileCode: [
    { required: true, message: '请输入手机验证码', trigger: 'blur' },
    { len: 6, message: '长度不正确', trigger: 'blur' },
  ],
}

@Component({})
export default class About extends Vue {
  @State((state: RootState) => state.login)
  private loginData!: LoginState
  private success: boolean = false
  private loading = false
  private countDownTime: number = 0
  private gotoLigonTimer: number = 0
  private sendDisabled: boolean = false

  @Action('login/signup') private signupEvt!: any
  @Action('login/sendMobileCode') private sendMobileCode!: any
  @Mutation('login/setStateData') private setStateData!: any

  protected render() {
    return (
      <div class={styles.container}>
        <div class={styles.header}>
          <img
            src={require('@/assets/help/logo-2x.png')}
            onClick={() => {
              this.$router.push({ name: 'homepage' })
            }}
          />
          <h1
            onClick={() => {
              this.$router.push({ name: 'homepage' })
            }}
          >
            浙江省政府电子印章系统
          </h1>
        </div>
        <div class={styles.signFormBox} v-show={!this.success}>
          <h1>欢迎注册</h1>
          <el-form
            {...{ props: { model: this.loginData, rules: loginRule } }}
            ref="loginForm"
            class={styles.loginComponent}
          >
            <el-form-item prop="licenseNumber" label-width="0">
              <el-input
                v-model={this.loginData.licenseNumber}
                placeholder="请输入身份证号码"
                autocomplete="off"
              />
            </el-form-item>
            <el-form-item prop="username" label-width="0">
              <el-input
                v-model={this.loginData.username}
                placeholder="请输入姓名"
                autocomplete="off"
              />
            </el-form-item>
            <el-form-item prop="phone" label-width="0">
              <el-input
                v-model={this.loginData.phone}
                placeholder="请输入手机号"
                autocomplete="off"
              />
            </el-form-item>
            <el-form-item prop="mobileCode" class="code-item" label-width="0">
              <el-input
                class="input-code"
                v-model={this.loginData.mobileCode}
                placeholder="请输入手机收到的验证码"
                autocomplete="off"
              />
              <button
                class={styles.mobileCode}
                onClick={this.getMobileCode}
                type="button"
                disabled={!!this.countDownTime || this.sendDisabled}
              >
                {this.countDownTime ? `${this.countDownTime}s` : '发送验证码'}
              </button>
            </el-form-item>
            <el-button
              class={{
                [styles.loginBtn]: true,
                'btn-primary': true,
                'btn-primary-hover': this.validField(),
              }}
              loading={this.loading}
              onClick={this.signup}
            >
              注册
            </el-button>
            <p class={styles.tips}>
              已有账号？
              <router-link to="/homepage/first?login=true">
                立即登录
              </router-link>
            </p>
          </el-form>
        </div>
        <div v-show={this.success} class={styles.signupSuccessBox}>
          <i class="el-icon-circle-check" />
          <h1>注册成功</h1>
          <p>如无法正常跳转请点击下方按钮跳转</p>
          <router-link to="/homepage/first?login=true">
            点击跳转({this.gotoLigonTimer}s)
          </router-link>
        </div>
        <div class={styles.footer}>
          <p>
            服务热线：4000878198转3(政务服务专线)
            主办单位：浙江省大数据发展管理局 技术支持：杭州天谷信息科技有限公司
          </p>
        </div>
      </div>
    )
  }

  private signup() {
    this.loginData.licenseNumber = this.loginData.licenseNumber.toUpperCase()
    const form = this.$refs.loginForm as ElForm

    form.validate(async (valid: boolean) => {
      if (valid) {
        this.loading = true
        this.signupEvt()
          .then((res: any) => {
            this.loading = false
            this.success = true
            this.countDown(
              3,
              (time: number) => {
                this.gotoLigonTimer = time
              },
              () => {
                this.$router.push({
                  name: 'homepage',
                  query: { login: 'true' },
                })
              }
            )
          })
          .catch((e: any) => {
            this.loading = false
          })
      }
    })
  }

  private reset() {
    this.setStateData({
      licenseNumber: '',
      username: '',
      phone: '',
      mobileCode: '',
      // 标记是注册状态
      signUpFlag: true,
    })
    this.$nextTick(() => {
      ;(this.$refs.loginForm as ElForm).clearValidate()
    })
  }

  private mounted() {
    this.reset()
  }

  private validField() {
    const { licenseNumber, username, phone, mobileCode } = this.loginData

    return !!licenseNumber && !!username && !!phone && !!mobileCode
  }

  private getMobileCode(e: Event) {
    e.stopPropagation()
    e.preventDefault()
    let hasErr = false

    this.loginData.mobileCode = ''

    const from = this.$refs.loginForm as ElForm
    from.validateField(['phone', 'licenseNumber', 'username'], data => {
      if (!!data) {
        hasErr = true
      }
    })

    if (hasErr) return
    this.sendDisabled = true

    this.sendMobileCode({
      mobile: this.loginData.phone,
    })
      .then((res: any) => {
        this.sendDisabled = false

        if (!this.countDownTime) {
          // 倒计时 90s
          this.countDown(90, (time: number) => {
            this.countDownTime = time
          })
        }
      })
      .catch((e: any) => {
        this.sendDisabled = false
      })
  }

  private countDown(times: number, step?: any, cb?: any) {
    if (step) step(times)
    let time = times

    const timer = setInterval(() => {
      if (time <= 0) {
        clearInterval(timer)
        if (cb) cb()

        return
      }

      time--
      if (step) step(time)
    }, 1000)
  }
}
